from django.template.loader import render_to_string
from config.settings import ALLOWED_HOSTS
from django.core.signing import Signer
from django.core.exceptions import ValidationError
from datetime import datetime


signer = Signer()


def get_path_upload_avatar(instance, file):
    """ Building a file path, format: (media)user_id/avatar/photo.jpg
    """
    return f'user_id_{instance.id}/avatar/{file}'


def get_path_upload_backgroundImg(instance, file):
    """ Building a file path, format: (media)user_id/backgroundImage/image.jpg
    """
    return f'user_id_{instance.id}/backgroundImage/{file}'

def validate_size_image(file_obj):
    """ Checking file size
    """
    megabyte_limit = 2
    if file_obj.size > megabyte_limit * 1024 * 1024:
        raise ValidationError(f"Максимальный размер файла {megabyte_limit}MB")


def send_activation_notification(user):
    """ Send activation notification to user email
    """
    if ALLOWED_HOSTS:
        host = f'http://{ALLOWED_HOSTS[0]}'
    else:
        host = 'http://localhost:8000'
    context = {'user': user, 'host': host, 'sign': signer.sign(user.username)}
    subject = render_to_string('email/activation_letter_subject.txt', context)
    body_text = render_to_string('email/activation_letter_body.txt', context)
    user.email_user(subject, body_text)


def get_path_upload_photo(instance, file):
    """ Building a file path, format: (media)/user_id/task_image/<int:year>/task_title/photo.jpg
    """
    print('+'*50, instance)
    try:
        name_folder = str(instance).split(' - ')[-1]
        name_folder = name_folder.replace(' ', '_')
    except Exception as e:
        name_folder = str(instance).split()[-1]
    year = str(datetime.now().year)
    return f'user_id_{instance.owner.id}/task_image/{year}/{name_folder}/{file}'


def get_path_upload_reward(instance, file):
    """ Upload reward image to: (media)/rewards/<int:year>/reward_name.png"""
    year = str(datetime.now().year)
    return f'rewards/{year}/{file}'
